import 'package:cbec_app/components/app_conifg.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:cbec_app/utils/GlobalData.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:umeng_common_sdk/umeng_common_sdk.dart';
import './routes/routes.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

class App extends StatefulWidget {
  const App({super.key});

  @override
  State<App> createState() => _AppState();
}

class _AppState extends State<App> {
  String currentVersion = ''; // 设置默认值，避免未赋值时出现错误

  @override
  void initState() {
    super.initState();
    _initializeApp();
  }

  Future<void> _initializeApp() async {
    await _initializeVersion();

    // 检查隐私协议是否通过
    if (AppData.isHaveAgree && currentVersion == AppData.versionNo) {
      _initializeUmeng(); // 初始化友盟
    }
  }

  Future<void> _initializeVersion() async {
    final info = await PackageInfo.fromPlatform();
    setState(() {
      currentVersion = info.version; // 使用 setState 更新版本号
    });
  }

  Future<void> _initializeUmeng() async {
    // 友盟初始化参数
    try {
      await UmengCommonSdk.initCommon(GlobalData.umengAndroidAppkey, GlobalData.umengIosAppkey, 'Umeng');
      print('友盟初始化成功');
    } catch (e) {
      print('友盟初始化失败: $e');
    }
    UmengCommonSdk.setPageCollectionModeManual();
  }

  @override
  Widget build(BuildContext context) {
    // 移除启动页
    FlutterNativeSplash.remove();

    // 如果版本号尚未加载，返回加载状态的占位界面
    if (currentVersion.isEmpty) {
      return const Center(child: CircularProgressIndicator());
    }

    return ScreenUtilInit(
        designSize: const Size(375, 690),
        builder: (context, child) {
          return AppConfig.appIsGrey
              ? ShaderMask(
                  shaderCallback: (bounds) {
                    return const LinearGradient(
                      colors: <Color>[Colors.grey, Colors.grey],
                    ).createShader(bounds);
                  },
                  child: normalApp())
              : normalApp();
        });
  }

  ///正常类APP
  Widget normalApp() {
    return GetCupertinoApp(
        theme: const CupertinoThemeData(
          brightness: Brightness.light, // 强制设置浅色模式
          primaryColor: CupertinoColors.systemBlue,
        ),
        title: '百大易购',
        locale: const Locale('zh'),
        localizationsDelegates: const [
          GlobalMaterialLocalizations.delegate, //指定本地化的字符串和一些其他的值
          GlobalWidgetsLocalizations.delegate, //定义 widget 默认的文本方向，从左到右或从右到左。
          GlobalCupertinoLocalizations.delegate, //对应的 Cupertino 风格（Cupertino 风格组件即 iOS 风格组件）
        ],
        supportedLocales: const [
          Locale('zh', 'CH'),
          // Locale('en', 'US'),
        ],
        getPages: Routes.pages,
        initialRoute: (currentVersion == AppData.versionNo && AppData.isHaveAgree) ? Routes.splash : Routes.startPrivacyPage, // 根据条件显示隐私协议页面
        defaultTransition: Transition.rightToLeft,
        transitionDuration: const Duration(milliseconds: 300),
        debugShowCheckedModeBanner: false,
        navigatorObservers: [FlutterSmartDialog.observer],
        builder: FlutterSmartDialog.init(
            toastBuilder: (msg) {
              return _customToast(msg);
            },
            builder: EasyLoading.init()));
  }

  ///自定义toast
  Widget _customToast(String msg) {
    return ConstrainedBox(
      constraints: BoxConstraints(
        maxWidth: 188.w,
      ),
      child: Container(
        padding: EdgeInsets.only(left: 10.w, right: 10.w, top: 6.h, bottom: 6.h),
        decoration: BoxDecoration(color: Colors.black, borderRadius: BorderRadius.circular(4)),
        child: Text(
          msg,
          style: const TextStyle(fontSize: 12, color: Colors.white),
        ),
      ),
    );
  }
}
